<template>
  <div class="flex items-center justify-between mb-6">
    <div
      class="flex items-center justify-start cursor-pointer"
      @click="handleGo"
    >
      <el-icon>
        <ArrowLeftBold />
      </el-icon>
      <span class="pl-5">{{ $t("收款帐户") }}</span>
    </div>
    <el-button
      :plain="true"
      class="plainButton"
      type="danger"
      @click="addBankCard"
      >{{ $t("添加收款账户") }}</el-button
    >
  </div>
  <el-card>
    <el-table :data="state.tableData" v-loading="loading">
      <template #empty>
        <p class="text-lg">{{ $t("还没有添加银行卡") }}</p>
      </template>
      <el-table-column
        prop="card_name"
        :label="$t('账户名称')"
        align="center"
      />
      <el-table-column
        prop="card_number"
        :label="$t('卡片尾号')"
        align="center"
      />
      <el-table-column
        prop="bank_name"
        :label="$t('银行名称')"
        align="center"
      />
      <el-table-column
        fixed="right"
        align="center"
        :label="$t('操作')"
        width="240"
      >
        <template #default="scope">
          <el-button
            round
            icon="MoreFilled"
            size="small"
            class="cursor-pointer"
            @click="edit(scope.row)"
            >{{ $t("编辑") }}
          </el-button>
          <el-button
            round
            icon="MoreFilled"
            size="small"
            class="cursor-pointer"
            @click="toDel(scope.row)"
            >{{ $t("删除") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-5">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageable.total"
        :default-page-size="pageable.pageSize"
        :default-current-page="pageable.pageNum"
        :page-sizes="[10, 25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <el-drawer v-model="addOrEditBankCard" :title="drawerTitle" @close="close">
    <el-form :model="state.bankCardForm" :rules="rules" ref="ruleFormRef">
      <el-form-item prop="card_number">
        <el-input
          v-model="state.bankCardForm.card_number"
          :placeholder="$t('VA-请输入银行账号')"
          type="number"
        />
      </el-form-item>
      <el-form-item prop="bank_country">
        <el-select
          v-model="state.bankCardForm.bank_country"
          :placeholder="$t('VA-请选择银行所在国家')"
          style="width: 100%"
        >
          <el-option
            v-for="item in state.countryList"
            :key="item.jc"
            :label="item.country"
            :value="item.jc"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="bank_name">
        <el-input
          v-model="state.bankCardForm.bank_name"
          :placeholder="$t('VA-请输入银行名称')"
        />
      </el-form-item>
      <el-form-item prop="bank_address">
        <el-input
          v-model="state.bankCardForm.bank_address"
          :placeholder="$t('VA-请输入银行地址')"
        />
      </el-form-item>
      <el-form-item prop="card_name">
        <el-input
          v-model="state.bankCardForm.card_name"
          :placeholder="$t('VA-请输入持卡人姓名')"
        />
      </el-form-item>
      <el-form-item prop="card_country">
        <el-select
          v-model="state.bankCardForm.card_country"
          :placeholder="$t('VA-请选择持卡人国家')"
          style="width: 100%"
        >
          <el-option
            v-for="item in state.countryList"
            :key="item.jc"
            :label="item.country"
            :value="item.jc"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="card_address">
        <el-input
          v-model="state.bankCardForm.card_address"
          :placeholder="$t('VA-请输入持卡人地址')"
        />
      </el-form-item>
      <el-form-item prop="currency">
        <el-select
          v-model="state.bankCardForm.currency"
          :placeholder="$t('VA-请选择银行账号币种')"
          style="width: 100%"
        >
          <el-option
            v-for="item in state.currencyList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="flex items-center justify-center w-full">
          <el-button
            :plain="true"
            class="plainButton"
            type="primary"
            @click="onSubmit(ruleFormRef)"
            style="width: 120px"
            >{{ $t("提交") }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import {
  getBankCardList,
  GetPhoneAreaCode,
  GetVaBankCurrency,
  addVABankCard,
  updateVABankCard,
  getVABankCardInfo,
  delVABankCardInfo,
} from "@/api/VAAccount";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();

const loading = ref(false);

const state = reactive({
  tableData: [],
  bankCardForm: {
    card_number: "",
    bank_country: "",
    bank_name: "",
    bank_address: "",
    card_name: "",
    card_country: "",
    card_address: "",
    currency: "",
  },
  currencyList: [],
  countryList: [],
});
// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const handleGo = () => {
  router.replace(`/VAAccount/userList`);
};

const getBankCard = async () => {
  const data = {
    page: pageable.pageNum,
    pagesize: pageable.pageSize,
    id: history.state.id,
  };
  try {
    loading.value = true;
    const { list, page } = await getBankCardList(data);
    state.tableData = list || [];
    pageable.total = page?.total_count || 0;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

const handleCurrentChange = async (number) => {
  pageable.pageNum = number;
  await getBankCard();
};
// 条数
const handleSizeChange = (number) => {
  pageable.pageSize = number;
  getBankCard();
};

const addOrEditBankCard = ref(false);
const drawerTitle = ref(`${t("添加收款账户")}`);
const oparType = ref("add");

const rules = reactive({
  card_number: [
    {
      required: true,
      message: t("VA-请输入银行账号"),
      trigger: "change",
    },
  ],
  bank_country: [
    {
      required: true,
      message: t("VA-请选择银行所在国家"),
      trigger: "change",
    },
  ],
  bank_name: [
    {
      required: true,
      message: t("VA-请输入银行名称"),
      trigger: "change",
    },
  ],
  card_name: [
    {
      required: true,
      message: t("VA-请输入持卡人姓名"),
      trigger: "change",
    },
  ],
  bank_address: [
    {
      required: true,
      message: t("VA-请输入银行地址"),
      trigger: "change",
    },
  ],
  card_address: [
    {
      required: true,
      message: t("VA-请输入持卡人地址"),
      trigger: "change",
    },
  ],
  card_country: [
    {
      required: true,
      message: t("VA-请选择持卡人国家"),
      trigger: "change",
    },
  ],
  currency: [
    {
      required: true,
      message: t("VA-请选择银行账号币种"),
      trigger: "change",
    },
  ],
});

const addBankCard = () => {
  state.bankCardForm = {};
  addOrEditBankCard.value = true;
  oparType.value = "add";
  drawerTitle.value = `${t("添加收款账户")}`;
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
};

const edit = async (row) => {
  addOrEditBankCard.value = true;
  drawerTitle.value = `${t("编辑收款账户")}`;
  oparType.value = "edit";
  const data = await getVABankCardInfo({ id: row.id });
  state.bankCardForm = data || {};
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
};

const ruleFormRef = ref();

const onSubmit = (formRef) => {
  formRef.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (oparType.value === "add") {
          const data = { ...state.bankCardForm, id: history.state.id };
          addVABankCard(data).then((res) => {
            ElMessage({
              message: t("添加成功"),
              type: "success",
            });
          });
        } else {
          const data = { ...state.bankCardForm };
          updateVABankCard(data).then((res) => {
            ElMessage({
              message: t("编辑成功"),
              type: "success",
            });
          });
        }
        addOrEditBankCard.value = false;
        state.bankCardForm = {};
        getBankCard();
      } catch {
        state.bankCardForm = {};
      }
    }
  });
};

const toDel = (row) => {
  ElMessageBox.confirm(`${t("确认删除吗?")}`, {
    confirmButtonText: `${t("确认")}`,
    cancelButtonText: `${t("取消")}`,
    type: "warning",
  })
    .then(() => {
      delVABankCardInfo({ id: row.id }).then((res) => {
        ElMessage({
          type: "success",
          message: `${t("删除成功")}`,
        });
        getBankCard();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `${t("取消")}`,
      });
    });
};

const close = () => {
  ruleFormRef.value.resetFields();
  addOrEditBankCard.value = false;
};

const getVaBankCurrency = async () => {
  try {
    const data = await GetVaBankCurrency();
    state.currencyList = data || [];
  } catch {}
};

const getPhoneAreaCode = async () => {
  try {
    const data = await GetPhoneAreaCode();
    state.countryList = data || [];
  } catch {}
};

onMounted(() => {
  getBankCard();
  getVaBankCurrency();
  getPhoneAreaCode();
});
</script>
<style lang="scss" scoped>
.el-card {
  border-radius: 10px;
}
</style>
